package com.xilihui.xlh.business.activitys;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tbruyelle.rxpermissions.RxPermissions;
import com.trello.rxlifecycle.android.ActivityEvent;
import com.weigan.loopview.LoopView;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.dialogs.DatePickerDialog;
import com.xilihui.xlh.business.dialogs.PickerViewDialog;
import com.xilihui.xlh.business.entities.AgentsEntity;
import com.xilihui.xlh.business.entities.Category;
import com.xilihui.xlh.business.entities.ItemsEntity;
import com.xilihui.xlh.business.entities.ShopEntity;
import com.xilihui.xlh.business.requests.AppointmentRequest;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.app.ToolBaseCompatActivity;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.rxbus.RxBus;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.ToastUtil;

import org.feezu.liuli.timeselector.TimeSelector;
import org.feezu.liuli.timeselector.Utils.TextUtil;

import java.security.Permission;
import java.security.Permissions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.Field;
import rx.functions.Action1;
import rx.subjects.BehaviorSubject;

/**
 * Created by Administrator on 2018/5/17.
 */

public class GoAppointmenActivity extends ToolBaseCompatActivity{

    @BindView(R.id.ll_shop_mine_appointmen)
    LinearLayout ll_shop;
    @BindView(R.id.ll_start_time)
    LinearLayout ll_start;
    @BindView(R.id.ll_end_time)
    LinearLayout ll_end_time;
    
    @BindView(R.id.tv_shopName)
    TextView tv_shopName;
    @BindView(R.id.tv_startTime)
    TextView tv_startTime;
    @BindView(R.id.tv_endTime)
    TextView tv_endTime;
    @BindView(R.id.tv_items)
    TextView tv_items;
    @BindView(R.id.tv_zuoweiType)
    TextView tv_zuoweiType;
    @BindView(R.id.et_notes)
    EditText et_notes;
    @BindView(R.id.tv_submit)
    TextView tv_submit;
    
    @BindView(R.id.iv_toolbar_right)
    ImageView iv_right;
    

    private Intent intent;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy.MM.dd HH:mm");
    Date date;
    Calendar calendar = Calendar.getInstance();
    int year;
    int month;
    int day;
    int hour;

    String startTimeStr = "";
    String endTimeStr = "";
    
    private int agent_id = -1;//门店id
    private int project_id = -1;//项目id
    private int seat_type = -1;//座位类型
    private long start_time = 0;
    private long end_time = 0;
    private String note = "";
    
    
    ArrayList<ItemsEntity.DataBean.SeatNameBean> zuoweiType = new ArrayList<>();
    ArrayList<ItemsEntity.DataBean> datas;
    ItemsEntity itemsEntity = null;
    boolean isScan = false;
    
    @Override
    public int getLayout() {
        return R.layout.activity_mine_appointmen;
    }

    @Override
    public String initTitle() {
        return null;
    }
    
    @OnClick(R.id.iv_toolbar_left)
    public void back(){
        finish();
    }
    
    @OnClick(R.id.iv_toolbar_right)
    public void qrcode(){

        new RxPermissions(GoAppointmenActivity.this)
                .request(Manifest.permission.CAMERA)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if(aBoolean){
                            startActivity(new Intent(GoAppointmenActivity.this,ScanActivity.class));
                            finish();
                        }else {
                            ToastUtil.toastShortNegative("您还未开启访问摄像头权限，请到应用管理中开启");
                        }
                    }
                });
        
       
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        setToolTitle("我要预约");
        setToolRightImage(R.mipmap.btn_flicking3);
        tv_submit.setEnabled(false);
        
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR_OF_DAY);
        
        startTimeStr = year+"-"+month+"-"+day;
        endTimeStr = (year+1)+"-12-12";
        
        
    }

    @Override
    public void initData() {
        
        itemsEntity = (ItemsEntity) getIntent().getSerializableExtra("data");
        String id = getIntent().getStringExtra("id");
        String shopName = getIntent().getStringExtra("shopName");
        
        //立即扫码 
        if(itemsEntity!=null){
            id = itemsEntity.getId();
            shopName = itemsEntity.getName();
            try {
                LogUtil.i("mylog","f:"+itemsEntity.getTime());
                Date date = format1.parse(itemsEntity.getTime());
                start_time = date.getTime()/1000;
                LogUtil.i("mylog","t"+start_time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv_shopName.setCompoundDrawables(null,null,null,null);
            tv_startTime.setCompoundDrawables(null,null,null,null);
            tv_shopName.setText(itemsEntity.getName());
            tv_startTime.setText(itemsEntity.getTime());
            ll_shop.setEnabled(false);
            ll_start.setEnabled(false);
            ll_end_time.setVisibility(View.GONE);
            
            isScan = true;
        }
        
        if(!TextUtil.isEmpty(id)){
            agent_id = Integer.valueOf(id);
            tv_shopName.setText(shopName);
        }
        
        RxBus.getDefault()
                .toObservable(AgentsEntity.class)
                .compose(this.<AgentsEntity>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<AgentsEntity>() {
                    @Override
                    public void call(AgentsEntity agentBean) {
                        tv_shopName.setText(agentBean.getName());
                        agent_id = Integer.valueOf(agentBean.getId());
                        //重新选择清空之前选择
                        project_id = -1;
                        seat_type = -1;
                        tv_items.setText("");
                        tv_zuoweiType.setText("");
                        handleSubmit();
                    }
                });
        
    }
    

    /**
     * 预约门店
     */
    @OnClick(R.id.ll_shop_mine_appointmen)
    public void appointmenStores(){
        intent = new Intent(this,AppointmentStoresActivity.class);
        startActivity(intent);
    }
    
    //选择预约开始时间
    @OnClick(R.id.ll_start_time)
    public void selectStartTime(){
        TimeSelector selector = new TimeSelector(GoAppointmenActivity.this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                tv_startTime.setText(time);
                try {
                    date = format.parse(time);
                    start_time = date.getTime()/1000;
                    LogUtil.i("mylog",start_time+"start——time");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                handleSubmit();
            }
        },startTimeStr,endTimeStr);
        
        selector.setIsLoop(false);
        selector.setMode(TimeSelector.MODE.YMDHM);
        selector.show();
        
    }
    
    //选择预约结束时间
    @OnClick(R.id.ll_end_time)
    public void selectEndTime(){
        
        TimeSelector endTimeSelect = new TimeSelector(GoAppointmenActivity.this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                try {
                    date = format.parse(time);
                    end_time = date.getTime()/1000;
                    if(end_time<=start_time){
                        ToastUtil.toastShortNegative("结束时间请大于开始时间");
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                tv_endTime.setText(time);
                handleSubmit();
            }
        },startTimeStr,endTimeStr);
        
        
        endTimeSelect.setIsLoop(false);
        endTimeSelect.setMode(TimeSelector.MODE.YMDHM);
        endTimeSelect.show();
        
    }
    
    
    
    //选择预约项目
    @OnClick(R.id.ll_items)
    public void items(){
        
        if(agent_id!=-1){
            AppointmentRequest.items(agent_id)
                    .compose(DoTransform.<ItemsEntity>applyLoading(this))
                    .compose(GoAppointmenActivity.this.<ItemsEntity>bindToLifecycle())
                    .subscribe(new HttpSubscriber<ItemsEntity>(this) {
                        @Override
                        protected void onSuccess(ItemsEntity entity) {
                            datas = (ArrayList<ItemsEntity.DataBean>) entity.getData();
                            if(datas.size()>0){
                                showXianmu();
                            }else {
                                ToastUtil.toastShortNegative("改门店没有预约项目,请重新选择门店");
                            }
                            
                        }

                        @Override
                        protected void onFail(String msg) {
                            ToastUtil.toastShortNegative(msg);
                        }
                    });
        }else {
            ToastUtil.toastShortNegative("请选择预约门店");
            return;
        }
        
    }
    
    public void showXianmu(){
        new PickerViewDialog<ItemsEntity.DataBean>(GoAppointmenActivity.this,datas,0){

            @Override
            protected void setItems(LoopView loopView, List<ItemsEntity.DataBean> list) {
                ArrayList<String> strData = new ArrayList<>();
                for (int i=0;i<list.size();i++){
                    strData.add(list.get(i).getName());
                }
                loopView.setItems(strData);
            }

            @Override
            protected void onConfirm(ItemsEntity.DataBean itemsEntity, int position) {
                tv_items.setText(itemsEntity.getName());
                zuoweiType.clear();
                zuoweiType.addAll(itemsEntity.getSeat_name());
                project_id = itemsEntity.getProject_id();
                if(zuoweiType.size()<1){
                    ToastUtil.toastShortNegative("该预约项目没有座位类型");
                }
                //清空之前选择的座位类型
                seat_type = -1;
                tv_zuoweiType.setText("");

                handleSubmit();
            }
        }.show();
    }
    
    //选择座位类型
    @OnClick(R.id.rl_type)
    public void selectType(){
        
        if(zuoweiType.size()>0){
            new PickerViewDialog<ItemsEntity.DataBean.SeatNameBean>(this,zuoweiType,0){

                @Override
                protected void setItems(LoopView loopView, List<ItemsEntity.DataBean.SeatNameBean> list) {
                    ArrayList<String> data = new ArrayList<>();
                    for (int i=0;i<list.size();i++){
                        data.add(list.get(i).getName());
                    }
                    loopView.setItems(data);
                }

                @Override
                protected void onConfirm(ItemsEntity.DataBean.SeatNameBean s, int position) {
                    tv_zuoweiType.setText(s.getName());
                    seat_type = s.getId();
                    handleSubmit();
                }
            }.show();
        }else {
            ToastUtil.toastShortNegative("请先选择预约项目");
        }
        
    }
    
    
    //提交我要预约
    @OnClick(R.id.tv_submit)
    public void submit(){
        
        note = et_notes.getText().toString();
        if(isScan){
            lijiyuyueSubmit();
        }else {
            tv_submit.setEnabled(false);
            AppointmentRequest.submit(this,agent_id,project_id,seat_type,start_time,end_time,note)
                    .compose(DoTransform.<BaseEntity>applyLoading(this))
                    .compose(GoAppointmenActivity.this.<BaseEntity>bindToLifecycle())
                    .subscribe(new HttpSubscriber<BaseEntity>(this) {
                        @Override
                        protected void onSuccess(BaseEntity entity) {
                            ToastUtil.toastLongPositive(entity.getMsg());
                            tv_submit.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            },1500);
                        }

                        @Override
                        protected void onFail(String msg) {
                            tv_submit.setEnabled(true);
                            ToastUtil.toastShortNegative(msg);
                        }
                    });
        }
        
        
    }
    
    //提交立即预约
    public void lijiyuyueSubmit(){
        tv_submit.setEnabled(false);
        AppointmentRequest.lijiyuyueSubmit(GoAppointmenActivity.this,agent_id+"",project_id+"",
                seat_type+"",start_time+"",note)
                .compose(DoTransform.<BaseEntity>applyScheduler(this,true))
                .compose(GoAppointmenActivity.this.<BaseEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<BaseEntity>(this) {
                    @Override
                    protected void onSuccess(BaseEntity entity) {
                        ToastUtil.toastLongPositive(entity.getMsg());
                        tv_submit.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        },1500);
                    }
                    
                    @Override
                    protected void onFail(String msg) {
                        tv_submit.setEnabled(true);
                        ToastUtil.toastShortNegative(msg);
                    }
                });
    }
    
    public void handleSubmit(){
        
        if(isScan){
            if(agent_id!=-1&&project_id!=-1&&seat_type!=-1&&start_time!=0){
                tv_submit.setSelected(true);
                tv_submit.setEnabled(true);
            }else {
                tv_submit.setSelected(false);
                tv_submit.setEnabled(false);
            }
        }else {
            if(agent_id!=-1&&project_id!=-1&&seat_type!=-1&&start_time!=0&&end_time!=0){
                tv_submit.setSelected(true);
                tv_submit.setEnabled(true);
            }else {
                tv_submit.setSelected(false);
                tv_submit.setEnabled(false);
            }
        }
        
       
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
